<template>
  <basic-container>
    <el-row>
      <el-col :span="11">
        <avue-crud
          :option="option"
          :table-loading="loading"
          :data="data"
          :page.sync="page"
          :permission="permissionList"
          :before-open="beforeOpen"
          v-model="form"
          ref="crud"
          @row-update="rowUpdate"
          @row-save="rowSave"
          @row-del="rowDel"
          @search-change="searchChange"
          @search-reset="searchReset"
          @selection-change="selectionChange"
          @current-change="currentChange"
          @size-change="sizeChange"
          @refresh-change="refreshChange"
          @on-load="onLoad"
        >
          <template slot="partnerNameSearch" class="partner">
            <el-input placeholder="请输入内容" v-model="form.partnerName" style="width: 150px">
              <el-button slot="append" icon="el-icon-search" @click="openPartnerModal()"></el-button>
            </el-input>
          </template>
          <!-- <template slot="searchMenu" slot-scope="{ scope }">
            <span> {{  }}</span>
          </template> -->
        </avue-crud>
        <common-modal-template ref="commonModalTemplate" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"> </common-modal-template>
      </el-col>
      <el-col :span="2">
        <div class="el-transfer-button" style="position: absolute; top: 50%; z-index: 100">
          <el-button type="primary" icon="el-icon-arrow-left" :disabled="selectionList2.length <= 0" class="btn" @click="moveToLeft"></el-button>
          <el-button type="primary" icon="el-icon-arrow-right" :disabled="selectionList.length <= 0" class="btn" @click="moveToRight"></el-button>
        </div>
      </el-col>
      <el-col :span="11">
        <el-tabs type="border-card" style="margin: 10px" v-if="isShowDetailTable">
          <el-tab-pane label="来料收货（供应商）详情">
            <avue-crud :option="option2" :data="data2" :permission="permissionList" ref="crud2" @selection-change="selectionChange2">
              <template slot="menuLeft">
                <el-button type="primary" :disabled="data2.length <= 0" class="btn" @click="submitFn" v-preventReClick>提 交</el-button>
              </template>
            </avue-crud>
          </el-tab-pane>
        </el-tabs>
        <!-- <el-row type="flex" justify="center">
              <el-button type="primary" :disabled="data2.length <= 0" style="width: 200px" class="btn" @click="submitFn" v-preventReClick>提  交</el-button>
          </el-row> -->
      </el-col>
    </el-row>
  </basic-container>
</template>

<script>
import { getList, submit } from '@/api/warehouse/material-receiving';
import { mapGetters } from 'vuex';
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';

export default {
  components: {
    CommonModalTemplate
  },
  data() {
    return {
      timer: null,
      form: {},
      tableOption: {},
      isShowDetailTable: false,
      loading: false,
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 1
      },
      rowData: {}, //行数据
      selectionList: [],
      selectionList2: [],
      data: [],
      data2: [],
      option: {
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchBtn: false,
        searchMenuPosition: 'right',
        searchMenuSpan: 4,
        dialogClickModal: false,
        border: true,
        height: 'calc(100vh - 440px)',
        viewBtn: false,
        addBtn: false,
        selection: true,
        printBtn: false,
        editBtn: false,
        delBtn: false,
        index: false,
        searchSpan: 5,
        menu: false,
        column: [
          {
            label: '采购单',
            prop: 'sheetNo',
            searchSpan: 8
            // search: true,
          },
          {
            label: '行号',
            prop: 'sheetLot'
          },
          {
            label: '物料编码',
            prop: 'partMasterCode'
          },
          {
            label: '物料名称',
            prop: 'partMasterName'
          },
          {
            label: '供应商',
            prop: 'partnerName',
            hide: true,
            search: true,
            searchType: 'search',
            formslot: true
          }
        ]
      },
      option2: {
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchBtn: false,
        searchMenuPosition: 'right',
        searchMenuSpan: 4,
        searchLabelWidth: 130,
        dialogClickModal: false,
        border: true,
        height: 'calc(100vh - 283px)',
        viewBtn: false,
        addBtn: false,
        selection: true,
        printBtn: false,
        editBtn: false,
        delBtn: false,
        index: false,
        searchSpan: 5,
        menu: false,
        column: [
          {
            label: '采购单',
            prop: 'sheetNo',
            width: 130
          },
          {
            label: '行号',
            prop: 'sheetLot',
            width: 50
          },
          {
            label: '物料编码',
            prop: 'partMasterCode'
          },
          {
            label: '物料名称',
            prop: 'partMasterName'
          },
          {
            label: '需求数量',
            prop: 'quantity'
          },
          {
            label: '已收数量',
            prop: 'completedQuantity',
            width: 80
          },
          {
            label: '本次收料数量',
            prop: 'receivingQuantity',
            type: 'number',
            minRows: 0,
            // precision: 10,
            controls: false,
            width: 100,
            cell: true,
            rules: [
              {
                required: true,
                message: '请输入本次收料数量',
                trigger: 'blur'
              },
              {
                required: true,
                trigger: 'blur',
                validator: (rule, value, callback) => {
                  //如果存在小数点，最多精确到10位
                  let reg = /^(?:\d*)(?:(\.\d{1,10})|(\d*))$/;
                  if (!reg.test(Number(value))) {
                    callback(new Error('输入小数点不能超过10位'));
                  } else {
                    callback();
                  }
                }
              }
            ]
          },
          {
            label: '生产日期',
            prop: 'vendorDate',
            type: 'datetime',
            width: 150,
            cell: true
          },
          {
            label: '送货单号',
            prop: 'supplierOrderNumber',
            width: 200,
            cell: true
          },
          {
            label: '供应商批次',
            prop: 'vendorLotNo',
            width: 100,
            cell: true
          },
          {
            label: '备注',
            prop: 'description',
            cell: true
          }
        ]
      }
    };
  },

  mounted() {
    // this.$nextTick(() => {
    //   this.$structuralSplit();
    // });
    this.$structuralSplit();
    this.isShowDetailTable = true;
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        viewBtn: this.vaildData(this.permission.scrapWareHouseManage_view, false)
      };
    }
  },
  methods: {
    rowSave(row, done, loading) {},
    rowUpdate(row, index, done, loading) {},
    rowDel(row) {},
    beforeOpen(done, type) {},
    searchReset() {
      this.form = {};
      this.data = [];
    },
    searchChange(params, done) {
      // this.query = params;
      // this.onLoad(params);
      // done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionChange2(list) {
      this.selectionList2 = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList({
        current: page.currentPage,
        size: page.pageSize,
        partnerId: this.form.partnerId,
        sheetType: 'PO',
        partnerType: 'SUPPLIER',
        statusList: '1,2',
        partnerName: this.form.partnerName
      }).then((res) => {
        let data = res.data.data;
        let data2 = this._orderBy(data.records, ['partMasterName']) || [];
        this._forEach(data2, (item) => {
          item['$cellEdit'] = true;
        });
        this.data = data2 || [];
        this.page.total = data.total;
        this.loading = false;
      });
    },
    /*
     * 搜索回车
     */
    searchEnter() {
      if (!this.form.partnerName) {
        this.$message({
          type: 'warning',
          message: '供应商不能为空!'
        });
        return;
      }
      this.page.pageSize = 15;
      this.page.currentPage = 1;
      this.onLoad(this.page, this.query);
    },
    /*
     * 移至左边
     */
    moveToLeft() {
      // this.data = this.data.concat(this.selectionList2);
      this.data2 = this._differenceWith(this.data2, this.selectionList2, (item1, item2) => {
        return item1.partMasterCode === item2.partMasterCode && item1.sheetNo === item2.sheetNo;
      });
      this.selectionClear();
    },
    /*
     * 移至右边
     */
    moveToRight() {
      let flag = false;
      this._uniqWith(this.selectionList.concat(this.data2), (arrVal, othVal) => {
        if (arrVal.partMasterCode === othVal.partMasterCode && arrVal.sheetNo === othVal.sheetNo) {
          flag = true;
        }
      });

      if (flag) {
        this.$message({
          type: 'warning',
          message: '当前和已选有重复，请重新选择!'
        });
        return;
      }

      let selectionList = this._forEach(this.selectionList, (item) => {
        if (this.form.partnerName) {
          item.partnerName = this.form.partnerName;
          item.partnerCode = this.form.partnerCode || item.partnerCode;
        }
      });

      this.data2 = this.data2.concat(selectionList);
      console.log(this.data2, 7777777777);
      // this.data = this._differenceWith(this.data, this.selectionList, (item1, item2) => {
      //   return item1.partMasterCode === item2.partMasterCode && item1.sheetNo === item2.sheetNo;
      // });
      this.selectionClear();
    },

    submitFn() {
      let paramMap = {
        receivingList: this._map(this.data2, (item) => {
          return {
            vendorCode: item.partnerCode,
            vendorName: item.partnerName,
            vendorLotNo: item.vendorLotNo,
            vendorDate: item.vendorDate,
            partnerId: this.form.partnerId,
            receiveQuantity: item.receivingQuantity,
            receiveType: 'SUPPLIER_BATCH',
            sheetNo: item.sheetNo,
            sheetDetailId: item.id,
            sheetId: item.sheetHeaderId,
            partNo: item.partMasterCode,
            partMasterId: item.partMasterId,
            quantity: item.quantity,
            description: item.description,
            supplierOrderNumber: item.supplierOrderNumber
          };
        })
      };
      submit(paramMap).then((res) => {
        this.selectionClear();
        this.onLoad(this.page);
        this.$message({
          type: 'success',
          message: '操作成功!'
        });
        this.data2 = [];
      });
    },
    /**
     * 选择模态框数据
     */
    async getSelectedRows(rowData, titleInfo) {
      this.$set(this.form, 'partnerName', this._get(rowData, 'name', ''));
      this.form.partnerId = rowData.id;
      this.form.partnerCode = rowData.partnerNo;
      this.onLoad(this.page);
    },
    /**
     * 供应商信息模态框
     */
    openPartnerModal() {
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择供应商信息（双击进行选择）',
        url: '/api/mes-admin/vendor/page',
        isPage: true,
        index: false,
        rowSelectionType: 'single',
        titleInfo: 'partnerInfo',
        columnDefs: [
          {
            label: '编码',
            prop: 'code',
            search: true
          },
          {
            label: '名称',
            prop: 'name',
            search: true
          },
          {
            label: '缩写',
            prop: 'abbreviation'
          },
          {
            label: '联系人',
            prop: 'principal'
          },
          {
            label: '联系方式',
            prop: 'contacts'
          },
          {
            label: '位置',
            prop: 'locations'
          }
        ]
      };
    },
    // 重新加载公用表格弹窗组件
    newKey() {
      this.timer = new Date().getTime();
    }
  }
};
</script>

<style lang="scss" scoped>
.el-transfer-button {
  position: absolute;
  left: 50%;
  top: 50%;
  z-index: 100;
  transform: translate(-50%, -50%);
}

.btn {
  background-color: #409eff;
  color: #fff;
}

.is-disabled {
  background-color: #fff !important;
  color: #cccccc !important;
}

::v-deep .avue-form__row {
  width: 250px;
}

.partner {
  ::v-deep .el-input__inner {
    width: 150px;
  }
}
::v-deep .el-tabs__item {
  color: #606266 !important;
  font-weight: bold;
}
</style>
